<template>
	<view>
		<view class="container">
			<!-- <headerView :title="title" :backBtn="true"></headerView> -->
			<cu-custom bgColor="bg-gradual-orange" :isBack="true">
				<block slot="content">订单中心</block>
			</cu-custom>
			<!-- tab 选择 -->
			<view class="tab-container">
				<view
					:class="['tab-item', { 'tab-item-active': selectTabIndex === index }]"
					v-for="(tab, index) in tabOptions"
					:key="index"
					@click="selectTab(index)"
				>
					{{ tab }}
				</view>
			</view>

			<!-- tab 内容 -->
			<view class="tab-content">
				<view class="tab-content-item" v-for="(item, index) in getCurrentTabData()" :key="index">
					<view class="tab-center">
						<view class="header-info">
							<view class="flexAc">
								<!-- <image :src="item.userAvatar" mode=""></image> -->
								<!-- <view class="name">{{ item.userName }}</view> -->
							</view>
							<view class="pay-type">{{ item.payStatusText }}</view>
						</view>
						<view class="shop-info">
							<image class="shop-info-image" :src="item.productImage" mode=""></image>
							<view class="shop-info-content">
								<view class="info-content-title">
									<view class="">{{ item.productName }}</view>
									<view class="">￥{{ item.productPrice }}</view>
								</view>
								<view class="info-content">
									<view class="">订单号: {{ item.orderSN }}</view>
									<view class="">X{{ item.productCount }}</view>
								</view>
							</view>
						</view>
						<view class="pay-money">实付款 ￥{{ item.totalPrice }}</view>
						<view class="edit-btn">
							<!-- <view class="delete-btn btn" @click="deleteOrder(item)">删除订单</view> -->
							<view class="pay-btn btn" @click="payOrder(item)">
								{{ item.payStatus === "unpaid" ? "付款" : "查看详情" }}
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 底部 tabbar -->
			<!-- <tabBar :selectIndex="selectIndex"></tabBar> -->
		</view>
	</view>
</template>

<script>
import headerView from "../../components/header/header.vue";
import tabBar from "../../components/tabBar/index.vue";
import banlance from "@/api/banlance";

export default {
	components: {
		tabBar,
		headerView,
	},
	data() {
		return {
			title: "会员订单",
			selectIndex: 1,
			tabOptions: ["全部", "待支付", "待发货", "已完成"],
			selectTabIndex: 0,
			orderData: {
				all: [],
				pendingPayment: [],
				pendingDelivery: [],
				completed: [],
			},
		};
	},
	methods: {
		selectTab(index) {
			this.selectTabIndex = index;
			this.getRecord();
		},
		getCurrentTabData() {
			switch (this.selectTabIndex) {
				case 0:
					return this.orderData.all;
				case 1:
					return this.orderData.pendingPayment;
				case 2:
					return this.orderData.pendingDelivery;
				case 3:
					return this.orderData.completed;
				default:
					return [];
			}
		},
		async getRecord() {
			const res = await banlance.getShopOrder({});
			if (res.code === 1) {
				const orders = res.data.map((order) => ({
					userAvatar: "/static/my_bg.png",
					userName: order.name,
					payStatus: order.pay_status,
					payStatusText: order.pay_status_text === "Unpaid" ? "待支付" : "已支付",
					productImage: order.thumb,
					productName: order.pname,
					productPrice: parseFloat(order.order_money),
					productDesc: `订单编号: ${order.order_sn}`,
					productCount: 1,
					totalPrice: parseFloat(order.pay_price),
					orderSN: order.order_sn,
					trackingNumber: order.tracking_number,
					orderTime: this.formatDate(order.createtime),
					tel:order.tel,
					address:order.address,

				}));

				this.orderData.all = orders;
				this.orderData.pendingPayment = orders.filter((order) => order.payStatus === "unpaid");
				this.orderData.pendingDelivery = orders.filter((order) => order.payStatus === "paid");
				this.orderData.completed = orders.filter((order) => order.payStatus === "completed");
			}
		},
		formatDate(timestamp) {
			const date = new Date(timestamp * 1000);
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, "0");
			const day = String(date.getDate()).padStart(2, "0");
			const hour = String(date.getHours()).padStart(2, "0");
			const minute = String(date.getMinutes()).padStart(2, "0");
			return `${year}-${month}-${day} ${hour}:${minute}`;
		},
		deleteOrder(item) {
			// console.log(JSON.stringify(item, null, 2)); // 美化输出
		  uni.showModal({
		    title: "确认删除",
		    content: "确定要删除该订单吗？",
		    success: async (res) => {
		      if (res.confirm) {
		        try {
		          const response = await banlance.deleteLevelOrder({ order_sn: item.orderSN });
		          if (response.code === 1) {
		            uni.showToast({
		              title: "删除成功",
		              icon: "success",
		            });
		            this.getRecord(); // 重新获取订单列表，更新界面
		          } else {
		            uni.showToast({
		              title: response.msg || "删除失败",
		              icon: "none",
		            });
		          }
		        } catch (error) {
		          uni.showToast({
		            title: "请求失败，请重试",
		            icon: "none",
		          });
		          console.error("删除订单失败:", error);
		        }
		      }
		    },
		  });
		},

		payOrder(item) {
			console.log(JSON.stringify(item, null, 2)); // 美化输出
		    const orderData = {
		        address: item.address,
		        tel: item.tel,
		        name: item.userName,
		        productImage: item.productImage,
		        productCount: item.productCount || 1, // 如果没有数量字段，默认 1
		        totalPrice: item.totalPrice,
		        productName: item.productName,
				orderSN:item.orderSN,
				payStatus:item.payStatus,
		    };
		
		    // console.log(JSON.stringify(orderData, null, 2)); // 美化输出
		    uni.navigateTo({
		        url: `/pages/my/balance/shoporder_pay?orderData=${encodeURIComponent(JSON.stringify(orderData))}`
		    });
		},

	},
	mounted() {
		this.getRecord();
	},
};
</script>



<style lang="less" scoped>
	.flexAc {
		display: flex;
		align-items: center;
	}

	.tab-container {
		display: flex;
		justify-content: space-around;
		// padding: 20rpx 0;
		background-color: #fff;

		.tab-item {
			font-size: 30rpx;
			padding: 30rpx 20rpx;
			width: 25%;
			height: 100%;
			cursor: pointer;
			position: relative;
			text-align: center;

			&.tab-item-active {
				color: #f76e00;

				&::before {
					content: "";
					position: absolute;
					left: 0;
					bottom: 0%;
					width: 100%;
					height: 6rpx;
					background-color: #ffd1aa;
				}
			}
		}
	}

	.tab-content {
		width: 100%;

		.tab-content-item {
			margin-top: 20rpx;
			width: 100%;
			height: 385rpx;
			background-color: #fff;
			border-radius: 10rpx;
			padding: 20rpx;

			.tab-center {
				width: 100%;
				margin: auto;

				.header-info {
					display: flex;
					justify-content: space-between;
					align-items: center;

					image {
						width: 35rpx;
						height: 35rpx;
						border-radius: 100%;
						vertical-align: middle;
						margin-right: 20rpx;
					}

					.pay-type {
						color: #f76e00;
					}
				}

				.shop-info {
					display: flex;
					justify-content: space-between;
					padding: 20rpx 0;

					.shop-info-image {
						width: 140rpx;
						height: 140rpx;
					}

					.shop-info-content {
						width: 77%;

						.info-content-title,
						.info-content {
							display: flex;
							width: 100%;
							justify-content: space-between;
						}

						.info-content {
							color: #bfbfbf;
							font-size: 24rpx;
							padding-top: 10rpx;
						}
					}
				}

				.pay-money {
					text-align: right;
				}

				.edit-btn {
					padding-top: 20rpx;
					display: flex;
					justify-content: flex-end;

					.btn {
						border: 2rpx solid #bfbfbf;
						width: 150rpx;
						text-align: center;
						padding: 6rpx 0;
						border-radius: 40rpx;
						margin-left: 20rpx;
					}

					.delete-btn {
						color: #4a4a4a;
					}

					.pay-btn {
						background-color: #ffd1aa;
						border: none;
					}
				}
			}
		}
	}
</style>